from rest_framework import serializers, status, generics
# 使用APIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from rest_framework.response import Response
import datetime,time,random
# 缓存配置
from django.core.cache import cache
from .models import User
from .serializers import UserSerializer, NewUserSerializer
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
    '''查看，编辑用户的界面'''
    queryset = User.objects.all()
    serializer_class = NewUserSerializer

class UserInfoSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

import coreapi
from rest_framework.permissions import AllowAny
from rest_framework.schemas import SchemaGenerator
from rest_framework.schemas.generators import LinkNode, insert_into
from rest_framework.renderers import *
from rest_framework_swagger import renderers
from rest_framework.response import Response
from django.conf import settings


class MySchemaGenerator(SchemaGenerator):
    
    def get_links(self, request=None):
        # from rest_framework.schemas.generators import LinkNode,
        links = LinkNode()

        paths = []
        view_endpoints = []
        for path, method, callback in self.endpoints:
            view = self.create_view(callback, method, request)
            path = self.coerce_path(path, method, view)
            paths.append(path)
            view_endpoints.append((path, method, view))

        # Only generate the path prefix for paths that will be included
        if not paths:
            return None
        prefix = self.determine_path_prefix(paths)

        for path, method, view in view_endpoints:
            if not self.has_view_permissions(path, method, view):
                continue
            link = view.schema.get_link(path, method, base_url=self.url)
            # 添加下面这一行方便在views编写过程中自定义参数.
            link._fields += self.get_core_fields(view)

            subpath = path[len(prefix):]
            keys = self.get_keys(subpath, method, view)

            # from rest_framework.schemas.generators import LinkNode, insert_into
            insert_into(links, keys, link)

        return links

    # 从类中取出我们自定义的参数, 交给swagger 以生成接口文档.
    def get_core_fields(self, view):
        return getattr(view, 'coreapi_fields', ())

class SwaggerSchemaView(APIView):
    _ignore_model_permissions = True
    exclude_from_schema = True

    # from rest_framework.permissions import AllowAny
    permission_classes = [AllowAny]
    # from rest_framework_swagger import renderers
    # from rest_framework.renderers import *
    renderer_classes = [
        CoreJSONRenderer,
        renderers.OpenAPIRenderer,
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        generator = MySchemaGenerator(title='测试的',description='''127.0.0.1:8000''')

        schema = generator.get_schema(request=request)

        # from rest_framework.response import Response
        return Response(schema)


def DocParam(name="default", location="query",required=True, description=None, type="string",*args, **kwargs):
    return coreapi.Field(name=name, location=location,required=required, description=description,type=type)



class GetKey(generics.GenericAPIView):
    serializer_class = UserInfoSerializer
    coreapi_fields=(
            DocParam("token"),
        )
    # def get(self, request):
    #     print(request.data)
    #     try:
    #         token = request.GET.get('token')
    #         json_data = {"message": "ok", "errorCode": 0, "data": {}}
    #         json_data['data']['token'] = token
    #         return Response(json_data)
    #     except Exception as e:
    #         print(e)
    #         return Response({"message": "未知错误", "errorCode": 1, "data": {}})

    
    def post(self,request):
        '''
        获取key接口
        '''
        print(request.data)
        try:
            serializer = self.get_serializer(data=request.data)
            if not serializer.is_valid():
                return Response({"message": str(serializer.errors), "errorCode": 4, "data": {}})
            data = (serializer.data)
            username = data.get('username')
            password = data.get('password')
            user = User.objects.filter(is_delete=False, name=username).first()
            if not user:
                return Response({"message": "用户不存在", "errorCode": 2, "data": {}})
            if user.password == password:
                return Response({"message": "登录成功", "errorCode": 0, "data": {'key':user.key}})
            else:
                return Response({"message": "密码错误", "errorCode": 0, "data": {}})
        except Exception as e:
            print(e)
            return Response({"message": "未知错误", "errorCode": 1, "data": {}})

def get_key():
    import random
    base_str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789'
    name = ''.join(random.sample(base_str, 12))
    return name

class registerSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

class RegisterAccount(generics.GenericAPIView):
    serializer_class = registerSerializer
    def post(self,request):
        '''
        注册用户接口
        '''
        print(request.data)
        try:
            serializer = self.get_serializer(data=request.data)
            if not serializer.is_valid():
                return Response({"message": str(serializer.errors), "errorCode": 4, "data": {}})
            data = (serializer.data)
            username = data.get('username')
            password = data.get('password')
            user = User.objects.filter(is_delete=False, name=username).first()
            if user:
                return Response({"message": "用户名已存在", "errorCode": 2, "data": {}})
            while True:
                key = get_key()
                check_key = User.objects.filter(is_delete=False,key=key)
                if not check_key:
                    break
            account = User()
            account.name = username
            account.password = password
            account.key = key
            account.save()
            return Response({"message": "注册成功，登录后获取KEY。", "errorCode": 0, "data": {}})
        except Exception as e:
            print(e)
            return Response({"message": "未知错误", "errorCode": 1, "data": {}})

import socket

# 获取本机IP
def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

class UploadFile(APIView):
    def post(self,request):
        '''
        上传接口
        '''
        try:
            key = request.GET.get('key') or None
            # print(request.META.get('HTTP_KEY'))
            print(key)
            if not key:
                return Response({"message": "请携带你的key上传文件！", "errorCode": 2, "data": {}})
            user = User.objects.filter(is_delete=False,key=key).first()
            if not user:
                return Response({"message": "未找到次key的用户，请核对后重新操作！！", "errorCode": 2, "data": {}})
            json_data = {"message": "ok", "errorCode": 0, 'data': {}}
            file_i = request.FILES.items()
            # 这里面filename是用户上传的文件的key upfile是用户上传的文件名
            image_size = 1024 * 1024 * 100
            image_check = ['png', 'jpg', 'jpeg', 'gif', 'bmp','zip','rar']
            import uuid,os
            upload_file_list = []
            upload_host_url_list = []
            for key_name,up_file in file_i:
                print(key_name,up_file.name,up_file.size,up_file.read)
                file_name = up_file.name
                file_size = up_file.size
                check_file = file_name.split('.')[-1]
                new_file_name = str(uuid.uuid1())
                if check_file.lower() not in image_check:
                    json_data['message'] = file_name + '不是规定的类型(png/jpg/jpeg/gif/bmp/zip/rar)！'
                    json_data['errorCode'] = 4
                    return Response(json_data)
                if file_size > image_size:
                    json_data['message'] = file_name + '文件超过100mb，无法上传！'
                    json_data['errorCode'] = 4
                    return Response(json_data)
                # 获取存储的文件名
                save_file_name = new_file_name + '.' + check_file
                # 获取当前文件的绝对路径
                base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
                upfile_base_dir = os.path.join(base_path, 'upload_file')
                user_dir_path = os.path.join(upfile_base_dir,str(user.name))
                is_have = os.path.exists(user_dir_path)
                if is_have:
                    user_up_path = os.path.join(user_dir_path,save_file_name)
                    print(user_up_path)
                else:
                    os.makedirs(user_dir_path)
                    user_up_path = os.path.join(user_dir_path, save_file_name)
                    print(user_up_path)
                with open(user_up_path, 'wb') as u_file:
                    for part in up_file.chunks():
                        u_file.write(part)
                host_file_url = 'http://' + settings.UPLOAD_IP + str(user.name) + '/' + save_file_name
                upload_file_list.append(save_file_name)
                upload_host_url_list.append(host_file_url)
                # json_data['data']['upload_file'] = upload_file_list
                json_data['data'] = upload_host_url_list

            # files = request.FILES
            # print(files['asd'])
            # uuid_list = str(uuid.uuid1()).split('-')
            # print(uuid_list[-1])
            return Response(json_data)
        except Exception as e:
            print(e)
            return Response({"message": "未知错误", "errorCode": 3})